import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { stripesConnect } from '@folio/stripes/core';
import get from 'lodash/get';
import {  MultiColumnList,IconButton } from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import SearchFrom from '../components/party-settings/search-from';
import FormSachet from '../components/party-settings/form-sachet';

class SettingsProperty extends Component {
  static manifest = Object.freeze({
    deleteId: { initialValue: '' },
    settingQuery: { initialValue: '' },
    resultCount: { initialValue: 10 },
    settingsRecords: {
      type: 'okapi',
      path: 'party/set',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      limitParam: 'size',
      records: 'partySetGroup',
      GET: {
        params: {
          query: '(isDel = 0 %{settingQuery} )'
        }
      }
    },
    httpValidatorInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/set',

    }
  });

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      deleteId: PropTypes.string,
      settingQuery: PropTypes.string,
      settingsRecords: PropTypes.object,
      httpValidatorInvoke: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      })
    }).isRequired
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      editOpen: false,
      editParams: {}
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
  }

  componentDidUpdate() {
    this.source.update(this.props, 'settingsRecords');
  }

  componentWillUnmount() {
    const { mutator } = this.props;

    mutator.settingQuery.replace('');
  }

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;
    if(!!formData.name){
      const query = ` and name = ${formData.name}* `;
      mutator.settingQuery.replace(query);
      if (this.source) {
        this.source.update(this.props, 'settingsRecords');
      }
    }

  };

  delData = formData => {
    const { mutator,intl } = this.props;
    // eslint-disable-next-line no-restricted-globals
    if (confirm(intl.formatMessage({id:"ui-party.loans.columns.party.deleteRemind"}))) {
      mutator.deleteId.replace(formData.id);
      mutator.httpValidatorInvoke.DELETE({ id: formData.id }).then(() => {
        mutator.deleteId.replace('');
      });
    }
  };

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  };

  openEditForm = params => {
    const flag = this.state.editOpen;
    this.setState({
      editOpen: !flag,
      editParams: params
    });
  };

  render() {
    const { resources } = this.props;
    const totalCount = this.source ? this.source.totalCount() : 0;
    if (this.source) {
      this.source.update(this.props, 'settingsRecords');
    }
    const dataList = get(resources, 'settingsRecords.records', []);

    const formatter = {
      serialNumber: (
        <FormattedMessage id="ui-party.loans.columns.serialNumber" />
      ),
      settingName: <FormattedMessage id="ui-party.loans.columns.party.sys.settingName" />,
      code: <FormattedMessage id="ui-party.loans.columns.party.sys.code" />,
      content: <FormattedMessage id="ui-party.loans.columns.party.sys.content" />,
      state: <FormattedMessage id="ui-party.loans.columns.party.sys.state" />,
      edit: (
        <FormattedMessage id="ui-party.loans.columns.operating" />
      )
    };

    return (
      <div data-test-application-settings-general-message  >
        {this.state.editOpen ? (
          <FormSachet
            editParams={this.state.editParams}
            spitOut={this.openEditForm}
            httpCall={this.props.mutator.settingsRecords}
            initialValues={this.state.editParams}
            httpValidatorInvoke={this.props.mutator.httpValidatorInvoke}
          />
        ) : (
          <div>
            <SearchFrom
              onSubmit={this.search}
              openEdit={() => {
                this.openEditForm();
              }}
            />
            <MultiColumnList
              interactive={false}
              height={500}
              isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
              totalCount={totalCount}
              virtualize
              contentData={dataList}
              onNeedMoreData={this.moreData}
              columnMapping={formatter}
              columnWidths={{
                serialNumber: '5%',
                settingName: '16%',
                code: '24%',
                content: '24%',
                state: '12%',
                edit: '10%'
              }}
              visibleColumns={[

                'settingName',
                'code',
                'content',
                'state',
                'edit'
              ]}
              formatter={{

                settingName: item => [<span>{item.name}</span>],
                state: item => {
                  if (item.state === 1) {
                    return <span><FormattedMessage id={"ui-party.messageTemplate.data.state.enable"}/></span>;
                  } else if (item.state === 0) {
                    return <span><FormattedMessage id={"ui-party.messageTemplate.data.state.disable"}/></span>;
                  }
                  return '';
                },
                edit: item => [
                  <IconButton
                      size="small"
                      icon="edit"
                      onClick={() => {
                        this.openEditForm(item);
                      }}
                  />
                  ,
                  <IconButton
                      icon="times"

                      aria-label="close"
                      onClick={() => {
                        this.delData(item);
                      }}
                  />
                ]
              }}
            />
          </div>
        )}
      </div>
    );
  }
}

export default stripesConnect(SettingsProperty);
